package com.easylinkin.linkappapi.function.typehandler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easylinkin.linkappapi.common.utils.StringUtil;
import com.easylinkin.linkappapi.devicetype.entity.DeviceType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

@MappedJdbcTypes(JdbcType.VARCHAR) // 数据库中该字段存储的类型
@MappedTypes(List.class)
public class RefDeviceTypeHandler extends BaseTypeHandler<List<DeviceType>> {

  @Override
  public void setNonNullParameter(PreparedStatement preparedStatement, int i,
      List<DeviceType> deviceTypes, JdbcType jdbcType) throws SQLException {
    Set<String> ids = deviceTypes.stream().map(DeviceType::getId).collect(Collectors.toSet());
    String idsStr = JSONObject.toJSONString(ids);
    preparedStatement.setObject(i,idsStr);
  }

  @Override
  public List<DeviceType> getNullableResult(ResultSet resultSet, String s) throws SQLException {
    String string = resultSet.getString(s);
    List<DeviceType> deviceTypes = commonResult(string);
    return deviceTypes;
  }

  @Override
  public List<DeviceType> getNullableResult(ResultSet resultSet, int i) throws SQLException {
    Object object = resultSet.getObject(i);
    if(object!=null){
      List<DeviceType> deviceTypes = commonResult((String) object);
      return deviceTypes;
    }
    return null;
  }

  @Override
  public List<DeviceType> getNullableResult(CallableStatement callableStatement, int i)throws SQLException {
    Object object = callableStatement.getObject(i);
    if(object!=null){
      List<DeviceType> deviceTypes = commonResult((String) object);
      return deviceTypes;
    }
    return null;
  }

  private List<DeviceType> commonResult(String s) {
    if(StringUtils.isNotBlank(s)){
      JSONArray ids = JSONObject.parseArray(s);
      List<DeviceType> deviceTypes = new ArrayList<>();
      ids.stream().forEach(item->{
        DeviceType type = new DeviceType();
        type.setId((String) item);
        deviceTypes.add(type);
      });
      return deviceTypes;
    }
    return null;
  }
}
